package com.ncepu.jjojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.ncepu.jjojcodesandbox.model.ExecuteCodeRequest;
import com.ncepu.jjojcodesandbox.model.ExecuteCodeResponse;
import com.ncepu.jjojcodesandbox.model.ExecuteMessage;
import com.ncepu.jjojcodesandbox.model.JudgeInfo;
import com.ncepu.jjojcodesandbox.utils.ProcessUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @author simon_jiang
 * @version 1.0
 */
@Service
public class JavaNativeCodeSandBoxOld implements CodeSandBox {

    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";
    private static final List<String> blackList = Arrays.asList("Files", "exec", "Thread.sleep");
    private static final WordTree WORD_TREE;
    static {
        WORD_TREE = new WordTree();
        WORD_TREE.addWords(blackList);
    }

    public static void main(String[] args) {
        JavaNativeCodeSandBoxOld javaNativeCodeSandBox = new JavaNativeCodeSandBoxOld();
        String code = ResourceUtil.readStr("testCode/simpleComputeArgs/Main.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("testCode/unsafecode/SleepError.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("testCode/unsafecode/MemoryError.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("testCode/unsafecode/RunFileError.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("testCode/unsafecode/WriteFileError.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("testCode/unsafecode/ReadFileError.java", StandardCharsets.UTF_8);
        ExecuteCodeRequest build = ExecuteCodeRequest.builder()
                .inputList(Arrays.asList("1 2", "1 3"))
                .code(code)
                .language("java")
                .build();
        javaNativeCodeSandBox.executeCode(build);
    }

    /**
     //         * 1. 把用户的代码保存为文件
     //         * 2. 编译代码，得到class文件
     //         * 3. 执行代码，得到输出结果
     //         * 4. 收集整理输出结果
     //         * 5. 文件清理，释放空间
     //         * 6. 错误处理，提升程序健壮性
     */
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest request) {

        List<String> inputList = request.getInputList();
        String code = request.getCode();

        // 检查代码中是否包含黑名单中的命令
        FoundWord foundWord = WORD_TREE.matchWord(code);
        if (foundWord != null) {
            System.out.println("检测到非法字符：" + foundWord.getFoundWord());
            return null;
        }

        //         * 1. 把用户的代码保存为文件
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        // 判断全局目录是否存在，不存在就新建
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        //         * 2. 编译代码，得到class文件
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodePath);
        try {
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileCmd, "编译");
            System.out.println(executeMessage);
        } catch (Exception e) {
            return getErrorResponse(e);
        }

        //         * 3. 执行代码，得到输出结果
        List<ExecuteMessage> runExecuteMessageList = new ArrayList<>();
        for(String inputArgs : inputList) {
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, inputArgs);
            try {
                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runCmd, "运行");
                System.out.println(executeMessage);
                runExecuteMessageList.add(executeMessage);
            } catch (Exception e) {
                return getErrorResponse(e);
            }
        }
        //         * 4. 收集整理输出结果
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        long maxTime = 0;
        for(ExecuteMessage executeMessage : runExecuteMessageList) {
            String errorExecuteMessage = executeMessage.getErrorMessage();
            if (errorExecuteMessage != null) {
                executeCodeResponse.setMessage(errorExecuteMessage);
                // 用户提交代码执行中出现错误
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if(time != null) {
                maxTime = Math.max(maxTime, time);
            }
        }
        // 正常运行结束
        if(outputList.size() == runExecuteMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
//        judgeInfo.setMemory(0L);
        executeCodeResponse.setJudgeInfo(judgeInfo);

        //         * 5. 文件清理，释放空间
        if(userCodeFile.getParentFile() != null) {
            boolean del = FileUtil.del(userCodeFile.getParentFile());
            System.out.println("删除文件：" + (del ? "成功" : "失败"));
        }
        System.out.println(executeCodeResponse);
        return executeCodeResponse;
    }

    /**
     * 获取错误响应
     *
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        // 表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }
}
